<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=\, initial-scale=1.0" />
    <title>localstorage的使用</title>
  </head>
  <body>
    <form action="https:www.imooc.com" method="post">
      <input type="text" name="username" />
      <input type="password" name="password" />
      <input type="submit" id="btn" value="登录" />
    </form>
    <script>
      // 直接使用setItem进行设置
      localStorage.setItem("key", "value");
      // length属性
      localStorage.length;
      // getItem获取数据,获取不存在的是null
      localStorage.getItem("key");
      // removeItem删除项目
      localStorage.removeItem();
      // clear()全部删除

      //   使用localStorage实现自动填充
      const loginForm = document.getElementById("login");
      const btn = document.getElementById("btn");
      const username = localStorage.getItem("username");
      if (username) {
        loginForm.username.value = username;
      }

      btn.addEventListener(
        "click",
        (e) => {
          e.preventDefault();
          //数据验证

          localStorage.setItem("username", loginForm.username.value);
          loginForm.submit();
        },
        false
      );
    </script>
  </body>
</html>
